"""
The MIT License (MIT)
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-video-stream
"""
from socketserver import UDPServer, DatagramRequestHandler
import traceback
import gc
from config import Commands
from capture import Capture


class Handler(DatagramRequestHandler):
	def handle(self):
		client_data, _ = self.request
		write = self.wfile.write

		try:
			# print('{} from {}'.format(client_data, self.client_address[0]))

			if client_data == Commands.REQUEST_ONE_FRAMES:
				globals()['count'] += 1
				write(Commands.SENDING_ONE_FRAME)
				write(capture.get_desktop_data((128, 64)))
		except KeyboardInterrupt:
			raise KeyboardInterrupt
		except:
			traceback.print_exc()


class Server(object):
	def __init__(self, host:str='', port:int=26688):
		self.host = host
		self.port = port
		self.__server = None
		self.__addr = (self.host, self.port)

	def start(self):
		self.__server = UDPServer(self.__addr, Handler)
		print('server started at ', self.__server.server_address)
		self.__server.serve_forever()

	def stop(self):
		if self.__server:
			self.__server.shutdown()
			print('server stopped')


def fps():
	global count
	import time

	while True:
		print('fps: ', count)
		count = 0
		time.sleep(1)


count = 0
capture = Capture(115)

if __name__ == '__main__':
	import _thread

	server = Server()

	try:
		_thread.start_new_thread(fps, ())
		server.start()
	except KeyboardInterrupt:
		server.stop()
		# exit(0)
